﻿using System.Security.Cryptography;
using System.Text;
using Wechat_PublicNumber.Entity;
using Wechat_PublicNumber.Model;
using Wechat_PublicNumber.SettingModel;

namespace Wechat_PublicNumber.Repository
{
    public class WxRepository : DataAccess
    {
        [Autowired]
        private WxSetting _wxSetting;

        [Autowired]
        private WxTemplateRepository _wxTemplateRepository;

        /// <summary>
        /// 微信接入校验绑定
        /// </summary>
        /// <returns></returns>
        public bool CheckWxBind(WeChatSignModel model)
        {
            var list = new List<string>
            {
                _wxSetting.Token,
                model.Timestamp,
                model.Nonce
            };
            list.Sort();

            byte[] array = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(string.Join("", list.ToArray())));
            StringBuilder stringBuilder = new StringBuilder();
            byte[] array2 = array;
            foreach (byte b in array2)
            {
                stringBuilder.AppendFormat("{0:x2}", b);
            }

            return model.Signature == stringBuilder.ToString();
        }

        /// <summary>
        /// 根据OpenID获取UserWebAccessToken
        /// </summary>
        /// <param name="openID"></param>
        /// <returns></returns>
        public async Task<UserWebAccessToken> GetUserWebAccessTokenByOpenID(string openID)
        {
            return await WXDb.Queryable<UserWebAccessToken>().Where(s => s.OpenID == openID).FirstAsync();
        }

        /// <summary>
        /// 保存UserWebAccessToken
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<long> SaveUserWebAccessToken(UserWebAccessToken data)
        {
            return await WXDb.SaveEntityAsync(data);
        }

        /// <summary>
        /// 根据OpenID获取UserInfo
        /// </summary>
        /// <param name="openID"></param>
        /// <returns></returns>
        public async Task<UserInfo> GetUserInfoByOpenID(string openID)
        {
            return await WXDb.Queryable<UserInfo>().Where(s => s.OpenID == openID).FirstAsync();
        }

        /// <summary>
        /// 根据OpenID获取UserInfo
        /// </summary>
        /// <param name="openID"></param>
        /// <returns></returns>
        public async Task<List<UserInfo>> GetUserInfoByOpenIDs(List<string> openID)
        {
            return await WXDb.Queryable<UserInfo>().Where(s => openID.Contains(s.OpenID)).ToListAsync();
        }

        /// <summary>
        /// 保存UserInfo
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<long> SaveUserInfo(UserInfo data)
        {
            return await WXDb.SaveEntityAsync(data);
        }
    }
}
